import { getMemberList, removeItem } from '@/services/member';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { Button, message, Space, Modal, Tag } from 'antd';
import React, { useRef, useState } from 'react';
import { FormattedMessage, useIntl, useAccess } from 'umi';
import AddEdit from './components/AddEdit';
import ViewDetail from './components/ViewDetail';
import PermissionWrapper from '@/components/PermissionWrapper';

const { confirm } = Modal;

const Member: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const access = useAccess();

  const [viewDrawerVisible, handleDrawerVisible] = useState<boolean>(false);
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.RuleListItem>();
  const [selectedRowsState, setSelectedRows] = useState<API.RuleListItem[]>([]);

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const getList = async (params: API.PageParams) => {
    const _params = {
      ...params,
      _page: params.current || 1,
      _limit: params.pageSize || 20,
    };
    delete _params.current;
    delete _params.pageSize;
    const { code, data } = await getMemberList(_params);
    return {
      data: data ? data.data : [],
      total: data ? data.count : 0,
      success: code === 0,
    };
  };

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = async (selectedRows: API.RuleListItem[]) => {
    if (!selectedRows) return;
    confirm({
      centered: true,
      content: intl.formatMessage({ id: 'public.deleteConfirmMessage' }),
      async onOk(): Promise<any> {
        if (!access.isAdmin) {
          message.warning(intl.formatMessage({ id: 'public.noDeletePermission' }));
          return false;
        }
        const hide = message.loading(intl.formatMessage({ id: 'public.deleteLoading' }));
        const { code } = await removeItem({
          id: selectedRows.map((row) => row.id),
        });
        hide();
        if (+code === 0) {
          message.success(intl.formatMessage({ id: 'public.successTips' }));
          setSelectedRows([]);
          actionRef.current?.reloadAndRest?.();
        }
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };

  const getColumns = (): any[] => {
    return [
      {
        title: <FormattedMessage id="member.username" />,
        dataIndex: 'username',
        width: 120,
      },
      {
        title: <FormattedMessage id="member.realname" />,
        dataIndex: 'realname',
        width: 120,
      },
      {
        title: <FormattedMessage id="member.phonenumber" />,
        dataIndex: 'phonenumber',
        width: 120,
      },
      {
        title: <FormattedMessage id="public.status" />,
        dataIndex: 'status',
        width: 80,
        hideInSearch: true,
        valueEnum: {
          0: {
            text: <FormattedMessage id="public.enabled" />,
            status: 'Success',
          },
          1: {
            text: <FormattedMessage id="public.disabled" />,
            status: 'Default',
          },
        },
      },
      {
        title: <FormattedMessage id="public.role" />,
        dataIndex: 'auth_groups',
        width: 320,
        render: (_: any, record: API.RuleListItem) => {
          return record.auth_groups.map((item: any) => (
            <Tag key={item.id} color="#FA541C">
              {item.name}
            </Tag>
          ));
        },
      },
      {
        title: <FormattedMessage id="public.updatetime" />,
        dataIndex: 'updatetime',
        valueType: 'dateTime',
        hideInSearch: true,
        width: 120,
      },
      {
        title: <FormattedMessage id="public.operate" />,
        dataIndex: 'option',
        valueType: 'option',
        width: 160,
        fixed: 'right',
        align: 'center',
        render: (_: any, record: API.RuleListItem) => [
          <PermissionWrapper key="view" name="system.memberManager.view">
            <a
              onClick={() => {
                setCurrentRow(record);
                handleDrawerVisible(true);
              }}
            >
              <FormattedMessage id="public.view" />
            </a>
          </PermissionWrapper>,
          record.id !== 1 && (
            <PermissionWrapper key="edit" name="system.memberManager.edit">
              <a
                onClick={() => {
                  setCurrentRow(record);
                  handleModalVisible(true);
                }}
              >
                <FormattedMessage id="public.edit" />
              </a>
            </PermissionWrapper>
          ),
          record.id !== 1 && (
            <PermissionWrapper key="delete" name="system.memberManager.delete">
              <a key="delete" onClick={() => handleRemove([record])}>
                <FormattedMessage id="public.delete" />
              </a>
            </PermissionWrapper>
          ),
        ],
      },
    ];
  };

  const columns: ProColumns<API.RuleListItem>[] = getColumns();

  return (
    <PageContainer
    // header={{ title: null }}
    >
      <ProTable<API.RuleListItem, API.PageParams>
        scroll={{ x: 'max-content' }}
        headerTitle={
          <Space size={16}>
            <PermissionWrapper key="batchDelete" name="system.memberManager.delete">
              <Button
                disabled={selectedRowsState?.length <= 0}
                type="default"
                icon={<DeleteOutlined />}
                onClick={() => handleRemove(selectedRowsState)}
              >
                <FormattedMessage id="public.batchDelete" />
              </Button>
            </PermissionWrapper>
          </Space>
        }
        actionRef={actionRef}
        rowKey="id"
        search={false}
        toolBarRender={() => [
          <PermissionWrapper key="add" name="system.memberManager.add">
            <Button
              type="primary"
              key="primary"
              onClick={() => {
                setCurrentRow(undefined);
                handleModalVisible(true);
              }}
              icon={<PlusOutlined />}
            >
              <FormattedMessage id="public.add" />
            </Button>
          </PermissionWrapper>,
        ]}
        options={false}
        request={getList}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
        tableAlertRender={false}
      />

      <AddEdit
        visible={createModalVisible}
        row={currentRow}
        onClose={() => handleModalVisible(false)}
        onSuccess={() => {
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
      />

      <ViewDetail
        visible={viewDrawerVisible}
        row={currentRow!}
        onClose={() => handleDrawerVisible(false)}
      />
    </PageContainer>
  );
};

export default Member;
